package com.unitedats.common.Servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.unitedats.common.Entity.SysUserLogin;
import com.unitedats.common.bo.JRBean;
import com.unitedats.common.bo.Message;
import com.unitedats.common.util.Common;
import com.unitedats.common.util.DBManager;
import com.unitedats.common.util.JasperUtil;

//import com.unitedats.common.util.Enums;

public class BasicServlet extends HttpServlet {

	@Autowired
	protected DBManager dbm;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			final WebApplicationContext ctx = WebApplicationContextUtils
					.getRequiredWebApplicationContext(getServletContext());
			ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this,
					AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
		} catch (BeansException e) {
			Common.log(e);
		}
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		Boolean noAuthRequired = Boolean.parseBoolean(this.getServletConfig().getInitParameter("NoAuthRequired"));

		if (noAuthRequired == null || noAuthRequired == false) {

			if (!accessAuthenticated(request)) {
				setMessage(request, new Message("You have to login first", Message.MESSAGE_TYPE.ERROR));
				response.sendRedirect(request.getContextPath() + "/LoginDisplay");
				return;
			} else if (!accessAuthorized(request)) {
				// request.setAttribute("javax.servlet.error.status_code",
				// HttpServletResponse.SC_FORBIDDEN);
				// response.setStatus(HttpServletResponse.SC_FORBIDDEN);
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				// response.sendRedirect("error/AccessDenied.jsp");
				return;
			}
		}
		super.service(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected boolean accessAuthenticated(HttpServletRequest request) {
		if (getSessionUser(request) != null)
			return true;
		return false;
	}

	protected boolean accessAuthorized(HttpServletRequest request) {
		// if (("" + Enums.USER_TYPE.RESTRICTED.getId())
		// .equals(this.getServletConfig().getInitParameter("notAllowedType"))
		// && WebUtil.sessionUserRestricted(request))
		// return false;
		return true;
		// int servletRole =
		// Integer.parseInt(this.getServletConfig().getInitParameter("roleId"));
		// Common.log(this.getServletConfig().getServletName() + " Role is " +
		// servletRole);
		// if (Arrays.asList(getUserRoles(request)).contains(servletRole))
		// return true;
		// return false;
	}

	protected void forward(HttpServletRequest request, HttpServletResponse response, String dest,
			boolean excludeInterface, boolean excludeMenu, boolean excludeHead) throws ServletException, IOException {
		request.setAttribute("excludeInterface", excludeInterface);
		request.setAttribute("excludeMenu", excludeMenu);
		request.setAttribute("excludeHead", excludeHead);
		request.setAttribute("dest", dest);
		request.getRequestDispatcher("Main.jsp").forward(request, response);
	}

	protected void viewHTMLReport(HttpServletRequest request, HttpServletResponse response, String dest,
			String reportTitle) throws ServletException, IOException {
		request.setAttribute("reportTitle", reportTitle);
		request.setAttribute("dest", dest);
		request.getRequestDispatcher("Report.jsp").forward(request, response);
	}

	protected void viewPDFReport(String reportName, Collection data, HashMap<String, Object> params,
			HttpServletResponse response) throws ServletException, IOException {
		JRBean b = new JRBean();
		// String path =
		// "D:\\EclipseWorkSpace\\7a2el\\MMP\\src\\main\\webapp\\WEB-INF\\reports\\";
		String path = getReportsRootPath() + "/";
		b.setJasperPrintPath(path + reportName);
		if (data != null && data.size() > 0)
			b.setDataSource(new JRBeanCollectionDataSource(data));
		else
			b.setDataSource(new JREmptyDataSource());
		b.setParams(params);
		try {
			JasperUtil.exportReportToResponseOutputStreamAsPDF(b, response);
		} catch (Exception ex) {
			Common.log(ex);
		}

	}

	protected void forwardToReportFilterScreen(HttpServletRequest request, HttpServletResponse response, String dest)
			throws ServletException, IOException {
		request.setAttribute("dest", dest);
		request.getRequestDispatcher("TemplateReportFilterScreen.jsp").forward(request, response);
	}

	protected void announceErorrMessage(HttpServletRequest request, HttpServletResponse response, String errorMsg)
			throws ServletException, IOException {
		setMessage(request, new Message(errorMsg, Message.MESSAGE_TYPE.ERROR));
		forward(request, response, "Announcement.jsp");
	}

	protected void forward(HttpServletRequest request, HttpServletResponse response, String dest)
			throws ServletException, IOException {
		forward(request, response, dest, false, false, false);
	}

	protected void basicForward(HttpServletRequest request, HttpServletResponse response, String dest)
			throws ServletException, IOException {
		request.getRequestDispatcher(dest).forward(request, response);
	}

	protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String dest)
			throws ServletException, IOException {
		response.sendRedirect(request.getContextPath() + "/" + dest);
	}

	protected void setSessionUser(HttpServletRequest request, SysUserLogin user) {
		request.getSession(true).setAttribute("user", user);
	}

	public SysUserLogin getSessionUser(HttpServletRequest request) {
		HttpSession s = request.getSession(false);
		if (s != null)
			return (SysUserLogin) s.getAttribute("user");
		return null;
	}

	protected void setMessage(HttpServletRequest request, Message message) {
		request.getSession(true).setAttribute("msg", message);
	}

	protected Message getMessage(HttpServletRequest request) {
		return (Message) removeSessionAttribute(request, "msg");
	}

	protected void setDestination(HttpServletRequest request, String dest) {
		request.getSession(true).setAttribute("dest", dest);
	}

	protected String getDestination(HttpServletRequest request) {
		return (String) removeSessionAttribute(request, "dest");
	}

	protected void setSessionAttribute(HttpServletRequest request, String attrName, Object attrValue) {
		request.getSession(true).setAttribute(attrName, attrValue);
	}

	protected Object getSessionAttribute(HttpServletRequest request, String attrName) {
		HttpSession s = request.getSession(false);
		return (s != null) ? s.getAttribute(attrName) : null;

	}

	protected Object removeSessionAttribute(HttpServletRequest request, String attrName) {
		Object o = null;
		HttpSession s = request.getSession(false);
		if (s != null) {
			o = s.getAttribute(attrName);
			s.removeAttribute(attrName);
		}
		return o;
	}

	protected String getReportsRootPath() {
		return getServletContext().getRealPath("/WEB-INF/") + "/reports";
	}

}
